1   /*
2    * Copyright (C) 2009 The Guava Authors
3    *
4    * Licensed under the Apache License, Version 2.0 (the "License");
5    * you may not use this file except in compliance with the License.
6    * You may obtain a copy of the License at
7    *
8    * http://www.apache.org/licenses/LICENSE-2.0
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS,
12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13   * See the License for the specific language governing permissions and
14   * limitations under the License.
15   */
16  
17  package com.google.common.primitives;
18  
19  import static com.google.common.base.Preconditions.checkArgument;
20  import static com.google.common.base.Preconditions.checkNotNull;
21  
22  import com.google.common.annotations.GwtCompatible;
23  
24  import java.util.Comparator;
25  
26  /**
27   * Static utility methods pertaining to {@code byte} primitives that
28   * interpret values as signed. The corresponding methods that treat the values
29   * as unsigned are found in {@link UnsignedBytes}, and the methods for which
30   * signedness is not an issue are in {@link Bytes}.
31   * 
32   * <p>See the Guava User Guide article on <a href=
33   * "http://code.google.com/p/guava-libraries/wiki/PrimitivesExplained">
34   * primitive utilities</a>.
35   *
36   * @author Kevin Bourrillion
37   * @since 1.0
38   */
39  // TODO(kevinb): how to prevent warning on UnsignedBytes when building GWT
40  // javadoc?
41  @GwtCompatible
42  public final class SignedBytes {
43    private SignedBytes() {}
44  
45    /**
46     * The largest power of two that can be represented as a signed {@code byte}. 
47     *
48     * @since 10.0
49     */
50    public static final byte MAX_POWER_OF_TWO = 1 << 6;
51    
52    /**
53     * Returns the {@code byte} value that is equal to {@code value}, if possible.
54     *
55     * @param value any value in the range of the {@code byte} type
56     * @return the {@code byte} value that equals {@code value}
57     * @throws IllegalArgumentException if {@code value} is greater than {@link
58     *     Byte#MAX_VALUE} or less than {@link Byte#MIN_VALUE}
59     */
60    public static byte checkedCast(long value) {
61      byte result = (byte) value;
62      if (result != value) {
63        // don't use checkArgument here, to avoid boxing
64        throw new IllegalArgumentException("Out of range: " + value);
65      }
66      return result;
67    }
68  
69    /**
70     * Returns the {@code byte} nearest in value to {@code value}.
71     *
72     * @param value any {@code long} value
73     * @return the same value cast to {@code byte} if it is in the range of the
74     *     {@code byte} type, {@link Byte#MAX_VALUE} if it is too large,
75     *     or {@link Byte#MIN_VALUE} if it is too small
76     */
77    public static byte saturatedCast(long value) {
78      if (value > Byte.MAX_VALUE) {
79        return Byte.MAX_VALUE;
80      }
81      if (value < Byte.MIN_VALUE) {
82        return Byte.MIN_VALUE;
83      }
84      return (byte) value;
85    }
86  
87    /**
88     * Compares the two specified {@code byte} values. The sign of the value
89     * returned is the same as that of {@code ((Byte) a).compareTo(b)}.
90     *
91     * <p><b>Note:</b> this method behaves identically to the JDK 7 method {@link
92     * Byte#compare}.
93     *
94     * @param a the first {@code byte} to compare
95     * @param b the second {@code byte} to compare
96     * @return a negative value if {@code a} is less than {@code b}; a positive
97     *     value if {@code a} is greater than {@code b}; or zero if they are equal
98     */
99    // TODO(kevinb): if Ints.compare etc. are ever removed, *maybe* remove this
100   // one too, which would leave compare methods only on the Unsigned* classes.
101   public static int compare(byte a, byte b) {
102     return a - b; // safe due to restricted range
103   }
104 
105   /**
106    * Returns the least value present in {@code array}.
107    *
108    * @param array a <i>nonempty</i> array of {@code byte} values
109    * @return the value present in {@code array} that is less than or equal to
110    *     every other value in the array
111    * @throws IllegalArgumentException if {@code array} is empty
112    */
113   public static byte min(byte... array) {
114     checkArgument(array.length > 0);
115     byte min = array[0];
116     for (int i = 1; i < array.length; i++) {
117       if (array[i] < min) {
118         min = array[i];
119       }
120     }
121     return min;
122   }
123 
124   /**
125    * Returns the greatest value present in {@code array}.
126    *
127    * @param array a <i>nonempty</i> array of {@code byte} values
128    * @return the value present in {@code array} that is greater than or equal to
129    *     every other value in the array
130    * @throws IllegalArgumentException if {@code array} is empty
131    */
132   public static byte max(byte... array) {
133     checkArgument(array.length > 0);
134     byte max = array[0];
135     for (int i = 1; i < array.length; i++) {
136       if (array[i] > max) {
137         max = array[i];
138       }
139     }
140     return max;
141   }
142 
143   /**
144    * Returns a string containing the supplied {@code byte} values separated
145    * by {@code separator}. For example, {@code join(":", 0x01, 0x02, -0x01)}
146    * returns the string {@code "1:2:-1"}.
147    *
148    * @param separator the text that should appear between consecutive values in
149    *     the resulting string (but not at the start or end)
150    * @param array an array of {@code byte} values, possibly empty
151    */
152   public static String join(String separator, byte... array) {
153     checkNotNull(separator);
154     if (array.length == 0) {
155       return "";
156     }
157 
158     // For pre-sizing a builder, just get the right order of magnitude
159     StringBuilder builder = new StringBuilder(array.length * 5);
160     builder.append(array[0]);
161     for (int i = 1; i < array.length; i++) {
162       builder.append(separator).append(array[i]);
163     }
164     return builder.toString();
165   }
166 
167   /**
168    * Returns a comparator that compares two {@code byte} arrays
169    * lexicographically. That is, it compares, using {@link
170    * #compare(byte, byte)}), the first pair of values that follow any common
171    * prefix, or when one array is a prefix of the other, treats the shorter
172    * array as the lesser. For example, {@code [] < [0x01] < [0x01, 0x80] <
173    * [0x01, 0x7F] < [0x02]}. Values are treated as signed.
174    *
175    * <p>The returned comparator is inconsistent with {@link
176    * Object#equals(Object)} (since arrays support only identity equality), but
177    * it is consistent with {@link java.util.Arrays#equals(byte[], byte[])}.
178    *
179    * @see <a href="http://en.wikipedia.org/wiki/Lexicographical_order">
180    *     Lexicographical order article at Wikipedia</a>
181    * @since 2.0
182    */
183   public static Comparator<byte[]> lexicographicalComparator() {
184     return LexicographicalComparator.INSTANCE;
185   }
186 
187   private enum LexicographicalComparator implements Comparator<byte[]> {
188     INSTANCE;
189 
190     @Override
191     public int compare(byte[] left, byte[] right) {
192       int minLength = Math.min(left.length, right.length);
193       for (int i = 0; i < minLength; i++) {
194         int result = SignedBytes.compare(left[i], right[i]);
195         if (result != 0) {
196           return result;
197         }
198       }
199       return left.length - right.length;
200     }
201   }
202 }